$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'suppOffline/erpsupplieroffline/list',
        datatype: "json",
        colModel: [			
			{ label: 'supplierId', name: 'supplierId', index: 'supplier_id', key: true, hidden:true },
		/*	{ label: '操作', name: 'opration', index: '', width: 40, align: 'center' ,
                formatter: function (value, options, row) {
                    // 审核状态:0.待审核,2.已通过,3.驳回
					var state = row.state;
					if (state == 0 || state == 3){
						return '<a href="javascript:;" onclick="return vm.auditModel('+ row.supplierId +')" onclick="">审核</a>';
					}else{
                        return '--';
					}
                }},*/
			{ label: '外协商名称', name: 'supplierName', index: 'supplier_name', width: 150, align: 'center' },
			{ label: '审核状态', name: 'state', index: 'state', width: 60, align: 'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.erpSupplierStateEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
			},
			{ label: '联系人', name: 'contactName', index: 'contact_name', width: 60 , align: 'center'},
			{ label: '联系人电话', name: 'contactTel', index: 'contact_tel', width: 80 , align: 'center'},
			{ label: '省市区', name: 'contactArea', index: 'contact_area', width: 80 , align: 'center'},
			{ label: '详细地址', name: 'contactAddr', index: 'contact_addr', width: 150 , align: 'center'},
            { label: '创建人', name: 'createName', index: 'create_name', width: 60 , align: 'center'},
            { label: '创建时间', name: 'createTime', index: 'create_time', width: 100 , align: 'center'},
			{ label: '审核人', name: 'auditName', index: 'audit_name', width: 80 , align: 'center'},
			{ label: '审核时间', name: 'auditTime', index: 'audit_time', width: 100 , align: 'center'},
			{ label: '驳回备注', name: 'remarksText', index: 'remarks_text', width: 100 , align: 'center'},
            {label: '备注', name: 'remarks', index: 'remarks', width: 80 , align: 'center'},
        ],
        viewrecords: true,
        height: window.innerHeight - 120,
        rowNum: 25,
        rowList : [25,50,75],
        rownumbers: true,
        rownumWidth: 40,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	// 隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            // 枚举参数
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.erpSupplierStateEnum = userData.erpSupplierStateEnum;
            // 省市区
            var regions = userData.regions;
            var options = JSON.parse(regions);
            vm.options = options;
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		erpSupplierOffline: {},
		/* 查询条件 */
		q: {
            supplierName: '',
            state: '',
            contactName: ''
		},
		/* 枚举类 */
		e: {
            erpSupplierStateEnum: []
		},
        formLabelWidth: '80px',
        auditFormVisible: false,
		/* 审核*/
		audit: {
			supplierId: '',
            auditRemark: '',
		},
        /* 省市区data */
        options: [],
        /* 省市区回显 */
        areaCascader: [],
	},
	methods: {
		query: function () {
			vm.reload();
		},
        reset: function () {
            vm.q.supplierName = '';
            vm.q.state = '';
            vm.q.contactName = '';
            vm.reload();
        },
		/* 外协商审核 */
        auditModel: function (id) {
        	vm.audit.supplierId = id;
        	vm.auditFormVisible = true;
        },
		/* 审核驳回 */
        auditReject: function () {
        	var remarksText = vm.audit.auditRemark;
        	if (isBlank(remarksText)){
        		alert("驳回备注不能为空");
        		return false;
			}

			var postData = {
                supplierId: vm.audit.supplierId,
                state: 3,
                remarksText: remarksText
            }

            $.ajax({
                type: "POST",
                url: baseURL + "suppOffline/erpsupplieroffline/audit",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code === 0){
                        vm.auditFormVisible = false;
                        vm.reload();
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		/* 审核通过 */
        auditSuccess: function () {

            var postData = {
                supplierId: vm.audit.supplierId,
                state: 2,
                remarksText: ''
            }

            $.ajax({
                type: "POST",
                url: baseURL + "suppOffline/erpsupplieroffline/audit",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code === 0){

                        vm.auditFormVisible = false;
						vm.reload();
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.erpSupplierOffline = {};
		},
		update: function (event) {
			var supplierId = getSelectedRow();
			if(supplierId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(supplierId)
		},
		saveOrUpdate: function (event) {
			var url = vm.erpSupplierOffline.supplierId == null ? "suppOffline/erpsupplieroffline/save" : "suppOffline/erpsupplieroffline/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.erpSupplierOffline),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var supplierIds = getSelectedRows();
			if(supplierIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "suppOffline/erpsupplieroffline/delete",
                    contentType: "application/json",
				    data: JSON.stringify(supplierIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(supplierId){
			$.get(baseURL + "suppOffline/erpsupplieroffline/info/"+supplierId, function(r){
                vm.erpSupplierOffline = r.erpSupplierOffline;
                /* 省市区 */
                var regionPath = r.erpSupplierOffline.regionPath;
                if (!isBlank(regionPath)){
                    // 字符型数组
                    var regionPathStringArr = regionPath.substring(1, regionPath.length-1).split(",");
                    // 整形数组
                    var regionPathIntArr = regionPathStringArr.map(function(data){
                        return +data;
                    });
                    vm.areaCascader = regionPathIntArr;
                }

            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
				postData: {
                    supplierName: vm.q.supplierName,
                    state: vm.q.state,
                    contactName: vm.q.contactName
				}
            }).trigger("reloadGrid");
		},
        /* 级联框选择事件 */
        handleItemChange: function(val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length-1];
            vm.erpSupplierOffline.contactAreaId = areaId;

            var lableObj = getCascaderObj(val, vm.options);
            var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.erpSupplierOffline.contactArea = lable;
        }
	}
});

/**
 * 省市区级联选择
 * @param val
 * @param opt
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children; return label;
            }
        }
        return null;
    });
}